/**
 * Jaxson ajax
 *
 * Copyright Remedy Interactive, licensed under Apache version 2 license:
 *
 *  http://www.apache.org/licenses/LICENSE-2.0.html
 *
 * This notice must remain in all java source files.
 */
package org.jaxson.struts.reverseAjax;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jaxson.config.ApplicationConfiguration;
import org.jaxson.struts.upload.BaseUploadAction;

/**
 * @author Joe Maisel
 *
 */
public class PollingAuthenticationFilter implements Filter
{
	private Log lager = LogFactory.getLog( PollingAuthenticationFilter.class );
	private static int sessionTimeout = -1;
	
	/**
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	@Override
	public void init( FilterConfig conf ) throws ServletException
	{
		
	}

	/**
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	@Override
	public void doFilter( ServletRequest req, ServletResponse res, FilterChain chain ) 
	throws IOException, ServletException
	{
		HttpServletRequest request = (HttpServletRequest)req;
		HttpSession session = request.getSession();
		
		if( session.getAttribute( BaseUploadAction.UPLOAD_IN_PROGRESS ) != null ){
			chain.doFilter( req, res );
			return;
		}
		
		if( sessionTimeout <= 0  ){
			sessionTimeout = 60 * Integer.parseInt( ApplicationConfiguration.getInstance().getProperty( "client.session.timeout" ) );
			lager.debug( "setting session timeout to " + (sessionTimeout/60) );
		}
		
		if( !request.getRequestURI().endsWith( "reverseAjax/poll.action" ) )
		{
			lager.debug( "resetting max inactive interval to " + (sessionTimeout/60) + " minutes" );
			request.getSession().setMaxInactiveInterval( sessionTimeout );
		}
		else
		{
			try
			{
				int interval = Integer.parseInt( ( ApplicationConfiguration.getInstance().getProperty( "client.reverse.ajax.poll.interval" ) ) );
				session.setMaxInactiveInterval( session.getMaxInactiveInterval() - interval );
				
				lager.debug( "session expires in " 
							+ (session.getMaxInactiveInterval()/60) + " minutes " 
							+ (session.getMaxInactiveInterval()%60) + " seconds" );
				
				if( session.getMaxInactiveInterval()/60 <= 1 ){
					//System.out.println( "do logout" );
				}
			}
			catch( NumberFormatException e )
			{
				e.printStackTrace();
			}
			catch( IOException e )
			{
				e.printStackTrace();
			}
		}
		
		chain.doFilter( req, res );
	}
	
	/**
	 * @see javax.servlet.Filter#destroy()
	 */
	@Override
	public void destroy()
	{
		
	}
}